package com.liuchao.maven.practice.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeoutException;

/**
 * @Description:
 * @Author: Liu Chao
 * @Date: 2018/8/12 10:37
 */
public class Confirm {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMQUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("test_queue_confirm_listener",false,false,false,null);
        channel.confirmSelect();

        final SortedSet<Long> confirmSet = Collections.synchronizedSortedSet(new TreeSet<Long>());

        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                if (multiple) {
                    System.out.println("---handleAck---");
                    confirmSet.headSet(deliveryTag + 1).clear();
                } else {
                    System.out.println("---handleAck------multiple false--- ");
                    confirmSet.remove(deliveryTag);
                }
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                if (multiple) {
                    System.out.println("---handleNAck---");
                    confirmSet.headSet(deliveryTag + 1).clear();
                } else {
                    System.out.println("---handleNAck------multiple false--- ");
                    confirmSet.remove(deliveryTag);
                }
            }
        });

        String msgStr = "hello confirm!";

        while (true) {
            long seqNo = channel.getNextPublishSeqNo();
            channel.basicPublish("", "test_queue_confirm_listener", null, msgStr.getBytes());
            confirmSet.add(seqNo);
        }
    }
}
